<!DOCTYPE html>
<html>

<head>
  <script src="/konva.min.js"></script>
  <meta charset="utf-8" />
  <title>Konva Sprite Demo</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #f0f0f0;
    }

    #punch {
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>

<body>
  <div id="container"></div>
  <button id="punch">Punch</button>
  <script>
    var width = window.innerWidth
    var height = window.innerHeight

    var stage = new Konva.Stage({
      container: 'container',
      width: width,
      height: height
    })

    var layer = new Konva.Layer()
    var animations = {
      idle: [
        // x, y, width, height (4 frames)
        2, 2, 70, 119,
        71, 2, 74, 119,
        146, 2, 300, 900,
        226, 2, 600, 1299
      ],
      punch: [
        // x, y, width, height (4 frames)
        2, 138, 74, 122,
        76, 138, 84, 122,
        346, 138, 120, 122
      ]
    }

    var imageObj = new Image()
    imageObj.onload = function () {
      var blob = new Konva.Sprite({
        x: 50,
        y: 50,
        // 加载的精灵图集
        image: imageObj,
        // 初始动画
        animation: 'idle',
        // 定义动画状态和帧。每个动画状态包含一系列帧  x y width height
        animations: animations,
        // 动画帧率
        frameRate: 7,
        // 初始帧索引
        frameIndex: 0
      })

      // add the shape to the layer
      layer.add(blob)

      // add the layer to the stage
      stage.add(layer)

      // start sprite animation
      blob.start()

      // resume transition
      document.getElementById('punch').addEventListener(
        'click',
        function () {
          blob.animation('punch')
          blob.on('frameIndexChange.button', function () {
            if (this.frameIndex() === 2) {
              setTimeout(function () {
                blob.animation('idle')
                blob.off('.button')
              }, 1000 / blob.frameRate())
            }
          })
        },
        false
      )
    }
    imageObj.src = 'https://www.bing.com/th?id=OHR.AncientOrkney_ROW1650150678_1920x1080.webp';
  </script>
</body>

</html>